package com.rem.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * 发送数据到kafka
 * 事物
 *
 * @author Rem
 * @date 2022-12-28
 */
public class CustomerProducerTransactions {

    public static void main(String[] args) {
        Properties properties = new Properties();
        //连接kafka
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9093,localhost:9094,localhost:9095");

        //是否开启幂等性，默认 true，开启幂等性
        properties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        // 指定事务id
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "tranactional_id_01");

        //配置kafka连接器以及key value序列化方式
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties, new StringSerializer(), new StringSerializer());

        //初始化事物
        kafkaProducer.initTransactions();
        //开启事物
        kafkaProducer.beginTransaction();


        try {
            for (int i = 0; i < 5; i++) {
                kafkaProducer.send(new ProducerRecord<>("first", "transactions" + i));
            }
            int i = 1 / 0;

            //提交事物
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            //放弃事物
            kafkaProducer.abortTransaction();
        } finally {
            kafkaProducer.close();
        }
    }
}
